<template>
  <div class="search-container">
    <el-card class="search-card" shadow="never">
      <div class="upload-area">
        <FileUpload v-model="imageUrl" @change="handleUpload"/>
        <div class="upload-tip">支持 jpg、png 格式图片</div>
      </div>
    </el-card>

    <!-- 搜索结果列表 -->
    <el-card class="result-card" shadow="never" v-loading="loading">
      <div slot="header">
        <span>搜索结果（{{ tableData.length}}条）</span>
      </div>
      <div class="table-box">
        <template v-if="tableData.length">
          <!-- PC端表格视图 -->
          <el-table
            v-if="!isMobile"
            :data="tableData"
            border
            style="width: 100%"
          >
            <el-table-column prop="id" label="编号" width="80" />
            <el-table-column prop="name" label="名称" min-width="120" />
            <el-table-column prop="category.name" label="分类" min-width="100" />
            <el-table-column prop="post_url" label="图片" min-width="120">
              <template slot-scope="scope">
                <el-image
                  style="height: 60px"
                  v-if="scope.row.post_url"
                  :src="scope.row.post_url"
                  :preview-src-list="[scope.row.post_url]"
                  fit="contain"
                />
              </template>
            </el-table-column>
            <el-table-column prop="count" label="库存" width="80" />
          </el-table>

          <!-- 移动端卡片视图 -->
          <div v-else class="mobile-cards">
            <el-card
              v-for="item in tableData"
              :key="item.id"
              class="product-card"
              shadow="hover"
            >
              <div class="card-content">
                <el-image
                  v-if="item.post_url"
                  :src="item.post_url"
                  :preview-src-list="[item.post_url]"
                  fit="cover"
                  class="product-image"
                />
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-category">
                    <span class="label">分类：</span>
                    <span>{{ item.category.name }}</span>
                  </div>
                  <div class="product-stock">
                    <span class="label">库存：</span>
                    <span>{{ item.count }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </template>

        <div v-else-if="!loading" class="empty-text">
          {{ imageUrl ? '未找到相似商品' : '请上传图片开始搜索' }}
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import {http, uploadFile} from '@/api'
import FileUpload from "@/components/FileUpload.vue";

export default {
  name: 'SearchIndex',
  components: {FileUpload},
  data() {
    return {
      imageUrl: '',
      loading: false,
      tableData: [],
      isMobile: false
    }
  },
  mounted() {
    this.checkDevice();
    window.addEventListener('resize', this.checkDevice);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkDevice);
  },
  methods: {
    checkDevice() {
      this.isMobile = window.innerWidth <= 768;
    },
    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传 JPG/PNG 格式图片!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 5MB!')
      }
      return isImage && isLt2M
    },
    // 处理图片上传
    async handleUpload() {
      try {
        this.loading = true
        this.tableData = []
        // 上传图片并搜索
        const res = await http.tiia.searchImage({
          url: this.imageUrl
        })
        if (res.data && res.data.ImageInfos.length) {
          const dataRes = await http.product.list({
            ids: res.data.ImageInfos.map(item => item.EntityId).join(',')
          })
          this.tableData = dataRes.data
        }
      } catch (error) {
        console.error('图片搜索失败:', error)
        this.$message.error('搜索失败，请重试')
      } finally {
        this.loading = false
      }
    },
  }
}
</script>

<style scoped lang="scss">
.search-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;

  @media screen and (max-width: 768px) {
    padding: 10px;
  }

  .search-card {
    .upload-area {
      display: flex;
      flex-direction: column;
      align-items: center;

      .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 300px;
        height: 300px;
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
          border-color: #409EFF;
        }

        @media screen and (max-width: 768px) {
          width: 200px;
          height: 200px;
        }
      }

      .upload-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: #8c939d;

        .el-icon-plus {
          font-size: 28px;
          margin-bottom: 8px;
        }
      }

      .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }

      .upload-tip {
        color: #909399;
        font-size: 12px;
        margin-top: 10px;
      }
    }
  }

  .result-card {
    .table-box {
      min-height: 200px;
      overflow-x: auto;
    }

    @media screen and (max-width: 768px) {
      .el-card__header {
        padding: 10px;
      }

      .el-card__body {
        padding: 10px;
      }
    }

    .mobile-cards {
      display: grid;
      gap: 10px;
      padding: 10px 0;

      .product-card {
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
        }

        .card-content {
          display: flex;
          gap: 12px;

          .product-image {
            width: 100px;
            height: 100px;
            border-radius: 4px;
            object-fit: cover;
          }

          .product-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 8px;

            .product-name {
              font-size: 16px;
              font-weight: bold;
              color: #303133;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }

            .product-category,
            .product-stock {
              font-size: 14px;
              color: #606266;

              .label {
                color: #909399;
              }
            }
          }
        }
      }
    }

    .empty-text {
      text-align: center;
      color: #909399;
      padding: 30px 0;
    }
  }
}
</style>
